import {Component, OnInit} from '@angular/core';
import * as moment from 'moment';
import {Router} from '@angular/router';
import {CouponService} from '../coupon.service';
import {AliyunOssOutputUrl} from '../../../../config/api';
import {NzMessageService, NzModalService } from 'ng-zorro-antd';

import {
  FormBuilder,
  FormGroup,
  FormControl,
  Validators
} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import {isInteger} from '@ng-bootstrap/ng-bootstrap/util/util';

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.scss'],
  providers: [CouponService]
})


export class AddComponent implements OnInit {

  aliyunOssOutputUrl =   AliyunOssOutputUrl;

  validateForm: FormGroup;
  options = [];

  _startDate = null;
  _endDate = null;

  termOfValidity = true;
  inStockValidity = 0;
  goodsValidity = true;
  checkedGoods = [];
  checkedGoodsTable = [];

  /* 添加商品弹框 */
  goodsModalVisible = false;
  goodsName: string;
  goodsList = [];
  groupList = [];
  allChecked = false;
  indeterminate = false;
  selectedGroup;  // 选中的商品分类

  page = 1;
  pageSize = 5;
  total;
  loading = false;
  status = '上架';

  constructor(private fb: FormBuilder,
              private router: Router,
              private couponService: CouponService,
              private _message: NzMessageService,
              ) {
    this.validateForm = this.fb.group({
      type: ['1', [Validators.required]],
      card_coupons_name: ['', [Validators.required, Validators.maxLength(30)]],
      face_value: ['', [Validators.required, Validators.min(1), Validators.max(999)], [this.integerValidators]], // 减免金额
      term_of_validity_type: [1, [Validators.required]], // 有效期类型1=跟随票券指定有效期，2=>跟随用户领取后有效时间
      in_stock_type: [0, [Validators.required]], // 0=不限，1=根据发行量限制
      condition_receive_quantity: ['', [Validators.required, Validators.min(1), Validators.max(255)], [this.lowerStockValidators]], // 每人可领取数量
      condition_lower_limit: ['', [Validators.required, Validators.min(1), Validators.max(99999999)], [this.lowerLimitValidators, this.integerValidators]], // 最低消费金额
      condition_use_in: [1, [Validators.required]], // 适用商品1=全部商品2=部分商品3=分类
      condition_can_use_in_pt: [0, [Validators.required]], // 是否适用拼团，0=不适用，1=适用
      publish_status: [0, [Validators.required]], // 卡券发行状态，0=正常 1=停止发行
      remark: ['', [Validators.maxLength(40)]], // 备注
      in_stock: [''], // 库存
      term_of_validity_time_start: [''],  // term_of_validity_type=1时,票券有效期开始时间
      term_of_validity_time_end: [''],  // term_of_validity_type=1时，票券有效期结束时间
      term_of_validity_start: [0],  // erm_of_validity_type=2时，有效期开始0=当天，1=第二天后···30=第30天后
      term_of_validity: [1, [Validators.max(9999)]],  // term_of_validity_type=2时，有效期：例如10天，最大值
      relation_id_json: ['']
    });
  }

  ngOnInit() {
    this.getGoodsList();
    this.getGroupList();
    for (let i = 0; i < 61; i++) {
      this.options.push(i);
    }
  }
  newArray = (len) => {
    const result = [];
    for (let i = 0; i < len; i++) {
      result.push(i);
    }
    return result;
  }
  _startValueChange = () => {
    this.termOfValidity = true;
    if (this._startDate > this._endDate) {
      this._endDate = null;
    }
  }
  _endValueChange = () => {
    this.termOfValidity = true;
    if (this._startDate > this._endDate) {
      this._startDate = null;
    }
  }
  _disabledStartDate = (startValue) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const now_time = now.getTime();
    if (!startValue || !this.validateForm.value.validity_end) {
      return startValue < now_time;
    }
    return (startValue.getTime() >= this.validateForm.value.validity_end.getTime()) || (startValue.getTime() <= Date.now());
  }
  _disabledEndDate = (endValue) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const now_time = now.getTime();
    if (!endValue || !this._startDate) {
      return endValue.getTime() < now_time;
    }
    return endValue.getTime() < this._startDate.getTime();
  }

  get _isSameDay() {
    return this._startDate && this._endDate && moment(this._startDate).isSame(this._endDate, 'day');
  }

  get _endTime() {
    return {
      nzHideDisabledOptions: true,
      nzDisabledHours: () => {
        return this._isSameDay ? this.newArray(this._startDate.getHours()) : [];
      },
      nzDisabledMinutes: (h) => {
        if (this._isSameDay && h === this._startDate.getHours()) {
          return this.newArray(this._startDate.getMinutes());
        }
        return [];
      },
      nzDisabledSeconds: (h, m) => {
        if (this._isSameDay && h === this._startDate.getHours() && m === this._startDate.getMinutes()) {
          return this.newArray(this._startDate.getSeconds());
        }
        return [];
      }
    };
  }
  getFormControl = (name) => {
    return this.validateForm.controls[name];
  }

  // 整数验证
  integerValidators = (control: FormControl): any => {
    return Observable.create(function (observer) {
      setTimeout(() => {
        if (!isInteger(control.value)) {
          observer.next({ error: true, notInteger: true });
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 100);
    });
  }

  lowerStockValidators = (control: FormControl): any => {
    const in_stock = this.validateForm.value.in_stock,
      stock_type = this.validateForm.value.in_stock_type;
    return Observable.create(function (observer) {
      setTimeout(() => {
        if (stock_type === 0) {
          observer.next(null);
        } else {
          if (control.value > in_stock) {
            observer.next({ error: true, lower: true });
          } else {
            observer.next(null);
          }
        }
        observer.complete();
      }, 1000);
    });
  }

  lowerLimitValidators = (control: FormControl): any => {
    const face_value = this.validateForm.value.face_value;
    return Observable.create(function (observer) {
      setTimeout(() => {
        if (control.value <= face_value) {
          observer.next({ error: true, lower: true });
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 1000);
    });
  }

  inStockValidators = (value): any => {
    if (value > 10000000) {
      this.inStockValidity = 2;
      return;
    } else {
      this.inStockValidity = 0;
    }
  }

  // 添加商品
  addGoods() {
    this.goodsModalVisible = true;
    this.page = 1;
    this.getGoodsList();
  }

  // 获取所有商品列表
  getGoodsList() {
    this.loading = true;
    this.couponService.getGoodsList(this.page, this.pageSize, this.selectedGroup, this.goodsName, this.status).subscribe(res => {
      this.total = res.data.total;
      this.goodsList = res.data.data;
      if (!!this.goodsList.length) {
        this.goodsList.every((val, idx, array) => {
          if (!this.checkedGoods.length) {
            val.checked = false;
            return true;
          } else {
            this.checkedGoods.every((val1, idx1, array1) => {
              if (val.id === val1.id) {
                val.checked = true;
                return false;
              }
              return true;
            });
            return true;
          }
        });
      }
      this.loading = false;
      this.refreshStatus();
    });
  }

  // 获取店铺商品类型列表
  getGroupList() {
    this.couponService.getGroupList().subscribe(res => {
      this.groupList = res.data.data;
      if (!!this.groupList.length) {
        this.groupList.every((val, idx, array) => {
          val.checked = false;
          return true;
        });
      }
    });
  }

  // 搜索商品
  searchGoods() {
    this.page = 1;
    this.getGoodsList();
  }

  checkedSingle(event: any, data: any) {
    if (event) {
      this.checkedGoods.push(data);
    } else {
      this.checkedGoods.every((val, idx, array) => {
        if (data.id === val.id) {
          this.checkedGoods.splice(idx, 1);
          return false;
        }
        return true;
      });
    }
    this.refreshStatus();
  }

  checkAll(value) {
    if (value) {
      this.goodsList.every((val, idx, array) => {
        if (!val.checked) {
          val.checked = true;
          this.checkedGoods.push(val);
        }
        return true;
      });
    } else {
      this.goodsList.every((val, idx, array) => {
        if (val.checked) {
          val.checked = false;
          this.checkedGoods.every((val1, idx1, array1) => {
            if (val.id === val1.id) {
              this.checkedGoods.splice(idx1, 1);
              return false;
            }
            return true;
          });
        }
        return true;
      });
    }
    console.log(this.checkedGoods);
    this.refreshStatus();
  }
  refreshStatus() {
    const allChecked = this.goodsList.every(value => value.checked === true) && this.goodsList.length != 0;
    const allUnChecked = this.goodsList.every(value => !value.checked);
    this.allChecked = allChecked;
    this.indeterminate = (!allChecked) && (!allUnChecked);
  }

  pageChange() {
    this.getGoodsList();
  }

  confirmAddGoods() {
    this.checkedGoodsTable = this.checkedGoods;
    this.goodsModalVisible = false;
    this.goodsValidity = true;
  }

  delCheckedGoods(idx: number) {
    this.checkedGoodsTable.splice(idx, 1);
    this.checkedGoods = JSON.parse(JSON.stringify(this.checkedGoodsTable));
  }

  // 提交表单
  submitForm() {
    if (this.validateForm.value.term_of_validity_type === 1 && (!this._startDate || !this._endDate)) {
      this.termOfValidity = false;
      return;
    } else if (this.validateForm.value.term_of_validity_type === 1 && (!!this._startDate && !!this._endDate)) {
      this.validateForm.value.term_of_validity_time_start = moment(this._startDate).format('YYYY-MM-DD') + ' ' + '00:00:00';
      this.validateForm.value.term_of_validity_time_end = moment(this._endDate).format('YYYY-MM-DD') + ' ' + '23:59:59';
    }
    if (this.validateForm.value.term_of_validity_type === 2 && !this.validateForm.value.term_of_validity) {
      this.termOfValidity = false;
      return;
    }
    if (this.validateForm.value.in_stock_type === 1) {
      if (!this.validateForm.value.in_stock) {
        this.inStockValidity = 1;
        return;
      } else if (this.validateForm.value.in_stock > 10000000) {
        this.inStockValidity = 2;
        return;
      }
    }
    if (this.validateForm.value.condition_use_in === 1) {
      this.validateForm.value.relation_id_json = 0;
    } else if (this.validateForm.value.condition_use_in === 2) {
      if (!!this.checkedGoodsTable.length) {
        const goods_id = [];
        this.checkedGoodsTable.every((val, idx, array) => {
          goods_id.push(val.id);
          return true;
        });
        this.validateForm.value.relation_id_json = JSON.stringify(goods_id);
      } else {
        this.goodsValidity = false;
        return;
      }
    } else {
      const category_id = [];
      this.groupList.every((val, idx, array) => {
        if (val.checked) {
          category_id.push(val.id);
        }
        return true;
      });
      if (!category_id.length) {
        this.goodsValidity = false;
        return;
      } else {
        this.validateForm.value.relation_id_json = JSON.stringify(category_id);
      }
    }
    this.couponService.addCoupon(this.validateForm.value).subscribe(res => {
      if (res.code === 2000) {
        this._message.create('success', `卡券添加成功`);
        this.router.navigate(['member/coupon/list']);
      } else {
        this._message.create('error', res.message);
      }
    });
  }


}
